package com.alinesno.cloud.operation.cmdb.third.wechat.controller;

import java.util.Date;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alinesno.cloud.operation.cmdb.common.constants.RunerEnum;
import com.alinesno.cloud.operation.cmdb.common.util.EmojiFilter;
import com.alinesno.cloud.operation.cmdb.controller.BaseController;
import com.alinesno.cloud.operation.cmdb.entity.UserEntity;
import com.alinesno.cloud.operation.cmdb.repository.UserRepository;
import com.alinesno.cloud.operation.cmdb.third.wechat.WechatConfig;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 微信用户认证授权
 * @author LuoAnDong
 * @since 2018年8月5日 下午11:38:22
 */
@Controller    // This means that this class is a Controller
@RequestMapping("/wx/auth") 
public class WechatOauthController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(WechatOauthController.class) ;
	
	@Value("${wechat.host}")  
	private String wechatHost ; 

	@Autowired
	private WechatConfig wechatConfig ; 
	
	@Autowired
	private UserRepository userRepository ; 

	/**
	 * 构造微信重定向路径
	 */
	@RequestMapping("path")
	public String redirect() {
		String callback = wechatHost+"/wx/auth/callback";
		String redirectUrl = wechatConfig.getInstance().oauth2buildAuthorizationUrl(callback, WxConsts.OAuth2Scope.SNSAPI_USERINFO, "") ; 
		
		logger.debug("redirect url = {}" , redirectUrl) ; 
		
		return "redirect:" + redirectUrl ; 
	}
	

	/**
	 * 微信认证重定向路径
	 * @return
	 * @throws WxErrorException 
	 */
	@RequestMapping("callback")
	public String callback(String code , HttpServletResponse response) throws WxErrorException {
		WxMpOAuth2AccessToken wxMpOAuth2AccessToken = wechatConfig.getInstance().oauth2getAccessToken(code);	
		
//		boolean valid = wechatConfig.getInstance().oauth2validateAccessToken(wxMpOAuth2AccessToken);
//		if(valid) {
//			wxMpOAuth2AccessToken = wechatConfig.getInstance().oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
//		}
		
		WxMpUser wxMpUser = null ; 
		try {
			wxMpUser = wechatConfig.getInstance().oauth2getUserInfo(wxMpOAuth2AccessToken, null);
		}catch(Exception e) {
			logger.error("获取用户信息失误.{}" , e);
			// 重新获取token
			wxMpOAuth2AccessToken = wechatConfig.getInstance().oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
			wxMpUser = wechatConfig.getInstance().oauth2getUserInfo(wxMpOAuth2AccessToken, null);
		}
		
		if(wxMpUser != null) {
		
			String filterNickName = EmojiFilter.filterNickName(wxMpUser.getNickname()) ; 
			wxMpUser.setNickname(filterNickName);
			logger.debug("昵称:{} , 去除表情包:{}" , wxMpUser.getNickname() , filterNickName);
			
			UserEntity user = userRepository.findByOpenId(wxMpUser.getOpenId()) ; 
			if(user == null) { 
				user = new UserEntity() ;
				try {
					// 微信昵称表情包处理
					BeanUtils.copyProperties(wxMpUser, user); 
					
					user.setAddTime(new Date()); //注册时间 
					user.setFieldProp(RunerEnum.STATUS_MEMBER.getCode());
					
					userRepository.save(user) ; 
				
					logger.debug("保存用户:{}成功" , user);
				}catch(Exception e) {
					logger.error("登陆失败:{}" , e);
				}
			}else { 
				// 跟进更新微信信息
				BeanUtils.copyProperties(wxMpUser, user); 
				user.setUpdateTime(new Date());
					
				userRepository.save(user) ; 
			}
			
//			if(StringUtils.isBlank(user.getPhone())) { //手机号为空
//				return "redirect:/phone/"+wxMpUser.getOpenId() ;  
//			}
			
			setCurrentSession(user) ; 
		}

		logger.info("wxMpUser = {}" , ToStringBuilder.reflectionToString(wxMpUser)); //获取到用户信息
		return "redirect:/" ; 
	}
	
}
